package util

import (
	"io"
	"os"

	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/log"
)

//三目运算符
func Triop[T any] (ret bool, a, b T) T {
	if ret {
		return a
	}

	return b
}

func DefaultStr(val string, def string) string {
	return Triop(val == "", def, val)
}

//数值类型
type NumberType interface {
	~int | ~uint | ~int8 | ~uint8 | ~int16 | ~uint16 |
	~int32 | ~uint32 | ~int64 | ~uint64 | ~uintptr |
	~float32 | ~float64
}

func DefaultNumber[T NumberType] (val T, def T) T {
	return Triop(val == 0, def, val)
}

func DefaultPtr[T *any] (val T, def T) T {
	return Triop(val == nil, def, val)
}


//日志打印器
var gbLogger *log.Logger
var gbErrorLogger *log.Logger

//初始化日志
func InitLogger(w io.Writer, o log.Options, forceInit ...bool) *log.Logger {
	forceUpdate := GetFuncDefaultArg(forceInit, false)

	if forceUpdate || gbLogger == nil {
		gbLogger = log.NewWithOptions(w, o)
	}

	styles := *log.DefaultStyles()
	styles.Levels[log.InfoLevel] = lipgloss.NewStyle().SetString("[OK]").Bold(true).Foreground(lipgloss.Color("#33bf3"))
	styles.Levels[log.WarnLevel] = lipgloss.NewStyle().SetString("[WARN]").Bold(true).Foreground(lipgloss.Color("#FFFFA5"))
	gbLogger.SetStyles(&styles)
	
	return gbLogger
}

//初始化日志
func InitErrorLogger(w io.Writer, o log.Options, forceInit ...bool) *log.Logger {
	forceUpdate := GetFuncDefaultArg(forceInit, false)

	if forceUpdate || gbErrorLogger == nil {
		gbErrorLogger = log.NewWithOptions(w, o)
	}

	styles := *log.DefaultStyles()
	styles.Levels[log.ErrorLevel] = lipgloss.NewStyle().SetString("[ERROR]").Bold(true).Foreground(lipgloss.Color("#E85A87"))
	gbErrorLogger.SetStyles(&styles)

	return gbErrorLogger
}

//获取日志记录器
func GetLogger() *log.Logger {
	if gbLogger == nil {
		return InitLogger(os.Stdout, log.Options{
			ReportTimestamp: false,
		})
	}
	return gbLogger
}

func GetErrorLogger() *log.Logger {
	if gbErrorLogger == nil {
		return InitErrorLogger(os.Stderr, log.Options{
			ReportTimestamp: false,
		})
	}

	return gbErrorLogger
}

//打印错误类型的日志
func PrintError(msg interface{}, keyValues ... interface{}) {
	GetErrorLogger().Error(msg, keyValues...)
}
//格式化打印错误类型的日志
func PrintErrorf(format string, args ... interface{}) {
	GetErrorLogger().Errorf(format, args...)
}

//打印信息类型的日志(蓝色)
func PrintSuccess(msg interface{}, keyValues ... interface{}) {
	GetLogger().Info(msg, keyValues...)
}
//格式化打印信息类型的日志(蓝色)
func LogSuccessf(format string, args ... interface{}) {
	GetLogger().Infof(format, args...)
}

//打印普通日志
func Print(msg interface{}, keyValues ... interface{}) {
	GetLogger().Print(msg, keyValues...)
}
//格式化打印普通日志
func Printf(format string, args ... interface{}) {
	GetLogger().Printf(format, args...)
}

//打印告警风格日志
func PrintWarn(msg interface{}, keyValues ... interface{}) {
	GetLogger().Warn(msg, keyValues...)
}
//格式化打印告警风格日志
func LogWarnf(format string, args ... interface{}) {
	GetLogger().Warnf(format, args...)
}


